package com.bigboss.knowstar.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.bigboss.knowstar.entity.Class;
import com.bigboss.knowstar.entity.Homework;
import com.bigboss.knowstar.entity.Notice;
import com.bigboss.knowstar.entity.User;
import com.bigboss.knowstar.entity.model.APIResult;
import com.bigboss.knowstar.entity.model.ClassItemData;
import com.bigboss.knowstar.entity.model.PageData;
import com.bigboss.knowstar.entity.model.ClassMemberData;
import com.bigboss.knowstar.exception.ClassException;
import com.bigboss.knowstar.exception.FileUploadException;
import com.bigboss.knowstar.service.impl.ClassServiceImpl;
import com.bigboss.knowstar.service.impl.LocalUploadServiceImpl;
import com.bigboss.knowstar.utils.ClassMemberListener;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.bigboss.knowstar.utils.ValidateData.validateData;

@RestController
@RequestMapping("/class")
public class ClassController {

    @Autowired
    private ClassServiceImpl classService;

    @Autowired
    private LocalUploadServiceImpl localUploadService;

    @PostMapping("")
    public APIResult classCreate(@RequestBody @Validated Class class_, BindingResult result) {
        try {
            ArrayList<String> data = validateData(result);
            if (data != null) {
                return APIResult.error(data);
            }
            classService.createClass(class_);
            return APIResult.success("班级创建成功");
        } catch (ClassException e) {
            return APIResult.error("班级创建失败:" + e.getMessage());
        }

    }

    @PutMapping("/{ClassId}")
    public APIResult classUpdate(@PathVariable Integer ClassId, @RequestBody Map<String, Object> fields) {
        try {
            classService.updateClass(ClassId, fields);
            return APIResult.success("班级更新成功");
        } catch (ClassException e) {
            return APIResult.error("班级更新失败:" + e.getMessage());
        }
    }

    @DeleteMapping("/{ClassId}")
    public APIResult classDelete(@PathVariable Integer ClassId) {
        try {
            classService.deleteClass(ClassId);
            return APIResult.success("班级删除成功");
        } catch (ClassException e) {
            return APIResult.error("班级删除失败:" + e.getMessage());
        }
    }

    @GetMapping("/{ClassId}")
    public APIResult classQueryByClassId(@PathVariable Integer ClassId) {
        try {
            Class class_ = classService.getClass(ClassId);
            return APIResult.success(class_);
        } catch (ClassException e) {
            return APIResult.error("班级查询失败:" + e.getMessage());
        }
    }

    @GetMapping("/members/{ClassId}")
    public APIResult queryAllMemberInClass(@PathVariable Integer ClassId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        PageHelper.startPage(page, limit);
        List<User> classMembers = classService.getClassMembers(ClassId);
        return APIResult.success(PageData.fromPage((Page<User>) classMembers));
    }

    @GetMapping("/homework/{ClassId}")
    public APIResult queryAllHomeworkInClass(@PathVariable Integer ClassId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        PageHelper.startPage(page, limit);
        List<Homework> classHomework = classService.getClassHomework(ClassId);
        return APIResult.success(PageData.fromPage((Page<Homework>) classHomework));
    }

    @GetMapping("/notices/{ClassId}")
    public APIResult queryAllNoticeInClass(@PathVariable Integer ClassId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        PageHelper.startPage(page, limit);
        List<Notice> classNotices = classService.getClassNotices(ClassId);
        return APIResult.success(PageData.fromPage((Page<Notice>) classNotices));
}

    @PostMapping("/members/upload/{ClassId}")
    public APIResult addClassMemberByExcel(@PathVariable Integer ClassId, MultipartFile file, HttpServletRequest req) {
        try {
            String filePath = localUploadService.uploadFile(file, req, "avatar-user");
            EasyExcel.read(filePath, ClassMemberData.class, new ClassMemberListener(classService, ClassId)).sheet().doRead();
            return APIResult.success("添加班级成员成功");
        } catch (FileUploadException | ExcelAnalysisException e) {
            return APIResult.error("添加班级成员失败:" + e.getMessage());
        }
    }

    @GetMapping("/list/{grade}")
    public APIResult queryAllClasses(@PathVariable String grade, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        PageHelper.startPage(page, limit);
        List<ClassItemData> classList = classService.getAllClasses(Integer.valueOf(grade));
        PageData pageData = new PageData((long) classList.size(), classList);
        return APIResult.success(pageData);
    }
}
